package com.wayhome.srpingbootmybatis.controller.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.wayhome.srpingbootmybatis.excel.Dr9225AccessInfo;
import com.wayhome.srpingbootmybatis.excelListener.Dr9225AccessListener;
import com.wayhome.srpingbootmybatis.mapper.FixmedinsMapper;
import com.wayhome.srpingbootmybatis.mbs.expertimport.dto.ExpertTemplate;
import com.wayhome.srpingbootmybatis.speacecase.HeadContentCellStyle;
import com.wayhome.srpingbootmybatis.speacecase.dto.FixmedinsFormData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/api/dr_9225_access")
public class Dr9225AccessInfoController {

    @Resource
    private FixmedinsMapper fixmedinsMapper;

    @PostMapping(value = "/queryFixmedinsName")
    public void queryFixmedinsName(MultipartFile file) {
        Dr9225AccessListener dr9225AccessListener = new Dr9225AccessListener(fixmedinsMapper);
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, Dr9225AccessInfo.class, dr9225AccessListener).sheet().doRead();
        }catch (Exception e) {
            log.error("解析9225调用情况文件失败", e);
        }
        try {
            List<Dr9225AccessInfo> list = dr9225AccessListener.getList();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");// 设置字符编码
            String fileName1 = URLEncoder.encode("支付资格接口调用情况", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName1 + ".xlsx"); // 设置响应头

            EasyExcel.write(response.getOutputStream(), Dr9225AccessInfo.class)
                    .registerWriteHandler(HeadContentCellStyle.myHorizontalCellStyleStrategy())
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
                    .sheet("9225调用情况")
                    .doWrite(list); //用io流来写入数据
        }catch (Exception e) {
            log.error("9225调用情况导出失败", e);
        }
    }
}
